from django.shortcuts import render
from django.http import JsonResponse, Http404
from article.models import Article, Category, Avatar
# from article.serializers import ArticleListSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework import generics
# from rest_framework.permissions import IsAdminUser
from article.permissions import IsAdminUserOrReadOnly
from rest_framework import viewsets
from rest_framework import filters
from article.serializers import ArticleSerializer, ArticleDetailSerializer
from article.serializers import CategorySerializer, CateoryDetailSerializer
from article.models import Tag
from article.serializers import TagSerializer
from article.models import Article
from article.serializers import AvatarSerializer

# @api_view(['GET', 'POST'])
# def article_list(request):
#     """
#     1.@api_view 装饰器允许视图接收 GET 、POST 请求，以及提供如 405 Method Not Allowed 等默认实现，
#         以便在不同的请求下进行正确的响应。
#     2.返回了 Response ，该对象由 Django 原生响应体扩展而来，它可以根据内容协商来确定返回给客户端的正确内容类型。
#         如果数据验证有误，还可以返回适当的状态码以表示当前的情况。
#     :param request:
#     :return:
#     """

#     if request.method == 'GET':
#         # 取出所有文章的 QuerySet
#         articles = Article.objects.all()
#         # 根据 QuerySet数据，创建一个序列化器
#         serializer = ArticleListSerializer(articles, many=True)
#         # 将序列化后的数据以json 的形式返回
#         return Response(serializer.data)
#     elif request.method == 'POST':
#         serializer = ArticleListSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             return Response(serializer.data, status=status.HTTP_201_CREATED)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# class ArticleDetail(APIView):
#     """文字详情视图-DRF-APIView"""
#     def get_object(self, pk):
#         """ 获取单个文章对象 """
#         try:
#             # pk 即主键，默认状态下就是id
#             return Article.objects.get(pk=pk)
#         except:
#             raise Http404
#
#     def get(self, request, pk):
#         article = self.get_object(pk)
#         serializer  = ArticleListSerializer(article)
#         # 返回json 数据
#         return Response(serializer.data)
#
#     def put(self, request, pk):
#         article = self.get_object(pk)
#         serializer = ArticleListSerializer(article, data=request.data)
#         # 验证提交的数据是否合法，不合法则返回400
#         if serializer.is_valid():
#             # 序列化器将持有的数据反序列化后，保存到数据中
#             serializer.save()
#             return Response(serializer.data)
#         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
#     def delete(self, request, pk):
#         article = self.get_object(pk)
#         article.delete()
#         # 删除成功后返回204
#         return Response(status=status.HTTP_204_NO_CONTENT)


# class ArticleList(generics.ListCreateAPIView):
#     """文章列表类视图"""
#     permission_classes = [IsAdminUserOrReadOnly]
#     queryset = Article.objects.all()
#     serializer_class = ArticleListSerializer
#
#     def perform_create(self, serializer):
#         """
#         perform_create: 从父类 ListCreateAPIView 继承,它在序列化数据真正保存之前调用，因此可以在这里添加额外的数据（即用户对象）。
#         :param serializer: ArticleListSerializer 序列化器实例，并且已经携带着验证后的数据。
#         它的 save() 方法可以接收关键字参数作为额外的需要保存的数据。
#         :return:
#         """
#         serializer.save(author=self.request.user)
#
#
# class ArticleDetail(mixins.RetrieveModelMixin,
#                     mixins.UpdateModelMixin,
#                     mixins.DestroyModelMixin,
#                     generics.GenericAPIView):
#     """文章详情类视图-DRF-Mixin"""
#     permission_classes = [IsAdminUserOrReadOnly]
#     queryset = Article.objects.all()
#     serializer_class = ArticleListSerializer
#
#     def get(self, request, *args, **kwargs):
#         return self.retrieve(request, *args, **kwargs)
#
#     def put(self, request, *args, **kwargs):
#         return self.update(request, *args, **kwargs)
#
#     def delete(self, request, *args, **kwargs):
#         return self.destroy(request, *args, **kwargs)

class ArticleViewSet(viewsets.ModelViewSet):
    """ 视图集 """
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    permission_classes = [IsAdminUserOrReadOnly]

    # 模糊匹配
    filter_backends = [filters.SearchFilter]
    search_fields = ['title']

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

    def get_serializer_class(self):
        if self.action == 'list':
            return ArticleSerializer
        else:
            return ArticleDetailSerializer


class CategoryViewSet(viewsets.ModelViewSet):
    """ 分类视图集 """
    queryset = Category.objects.all()
    serializer_class = CategorySerializer
    permission_classes = [IsAdminUserOrReadOnly]
    pagination_class = None

    def get_serializer_class(self):
        if self.action == 'list':
            return CategorySerializer
        else:
            return CateoryDetailSerializer


class TageViewSet(viewsets.ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [IsAdminUserOrReadOnly]
    pagination_class = None


class AvatarViewSet(viewsets.ModelViewSet):
    """ 标题图-视图集 """
    queryset = Avatar.objects.all()
    serializer_class = AvatarSerializer
    permission_classes = [IsAdminUserOrReadOnly]
